<?php

namespace app\admin\controller\yalimedia;

use addons\yalimedia\library\AlibabaCloundHelper;

use app\admin\model\YalimediaCourseUser;
use app\common\model\CourseQuestion;
use app\admin\model\yalimedia\course\Content;
use app\admin\model\yalimedia\course\Unit;
use app\common\controller\Backend;
use fast\Tree;
use think\Request;
use think\Cache;
use think\Exception;

use app\common\model\CourseQuestion as CourseQuestionModel;
use app\common\model\CourseQuestionCategory as CourseQuestionCategoryModel;


/**
 * 课程
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{

    protected $noNeedRight = ['add_content','edit_content','add_unit','edit_unit','del_unit','del_content','select_video'];
    public $type = ['2'=>'音频','3'=>'视频'];
    /**
     * Course模型对象
     * @var \app\admin\model\yalimedia\Course
     */
    protected $model = null;

    public function _initialize()
    {
        $this->request->filter(['strip_tags', 'trim']);
        
        parent::_initialize();
        $this->model = new \app\admin\model\yalimedia\Course;
//        if(input('pid',0)){
//
//            $this->model->whereNotIn('id',YalimediaCourseUser::where('user_id',input('pid',0))->select());
//        }
        $teacherModel = new \app\admin\model\yalimedia\Teacher();
        $teacherList = $teacherModel->order("weigh asc")->select();

        $this->view->assign('teacherList', $teacherList);

        $categoryModel = new \app\admin\model\yalimedia\course\Category();

        $tree = Tree::instance();
        $tree->init(collection($categoryModel->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $categorydata = [];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }

        $this->view->assign("parentList", $categorydata);

    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->whereNotIn('id',collection(YalimediaCourseUser::where('user_id',input('pid',0))->select())->column('course_id'))
                ->order($sort, $order)
                ->paginate($limit);
            
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign('pid',input('pid',0));
        return $this->view->fetch();
    }
    /**
     * 目录排序
     */
    public function unit_sort(){
        if ($this->request->isAjax()) {
            $params = $this->request->post("row/a");

            $unitModel = new \app\admin\model\yalimedia\course\Unit();
            $row = $unitModel->where(['id'=>$params['id'],'course_id'=>$params['course_id']])->find();
            if(empty($row)){
                $this->error("当前记录不存在");
            }
            $weigh = $row['weigh'];
            $new_weigh = $params['weigh'];
            \app\admin\model\yalimedia\course\Unit::sort($row['course_id'],$row['id'],$weigh,$new_weigh);
            $this->success("请求成功");
        }

        $id = $this->request->param('ids');
        $unitModel = new \app\admin\model\yalimedia\course\Unit();
        $row = $unitModel->where(['id'=>$id])->find();

        $this->assign('row',$row);
        return $this->view->fetch();
    }

    /**
     * 内容排序
     */
    public function content_sort(){
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            //查看权限
            $unitModel = new Content();
            $row = $unitModel
                ->alias("a")
                ->field("a.*")
                ->join("yalimedia_course b","a.course_id=b.id","inner")
                ->where(['a.id'=>($params['id'])])
                ->find();
            if(empty($row)){
                return json(array('code'=>-1,'msg'=>"当前课程不存在"));
            }

            $weigh = $row['weigh'];
            $new_weigh = $params['weigh'];

            Content::sort($row['course_id'],$row['unit_id'],$row['id'],$weigh,$new_weigh);
            $this->success("请求成功");
        }

        $id = $this->request->param('ids');
        $unitModel = new Content();
        $row = $unitModel
            ->alias("a")
            ->field("a.*")
            ->join("yalimedia_course b","a.course_id=b.id","inner")
            ->where(['a.id'=>($id-9000)])
            ->find();
        if(empty($row)){
            return json(array('code'=>-1,'msg'=>"当前课程不存在"));
        }
        $this->assign('row',$row);
        return $this->view->fetch();
    }



    /**
     * 设置学习内容
     */
    public function content($ids){
        $row = $this->model->get($ids);
        if ($this->request->isAjax()) {
            //获取目录
            $courseUnitModel = new \app\admin\model\yalimedia\course\Unit();
            $courseUnit = collection($courseUnitModel->field("id,unit_name as title")->where(['course_id'=>$ids])->order("weigh asc,id asc")->select())->toArray();
            $data = [];
   
            foreach($courseUnit as $v){
                $v['pid']  = 0;
                $v['cate'] = "unit";
                $data[]    = $v;

                $courseContentModel = new Content();
                $courseContent = collection($courseContentModel->field("id,unit_id as pid,title,type")->where(['course_id'=>$ids,'unit_id'=>$v['id']])->order("weigh asc,id asc")->select())->toArray();
          
                foreach($courseContent as $vv){
                    $vv['id']   = $vv['id']+9000;
                    $vv['cate'] = "content";
                    $data[] = $vv;
                }
            }

            $tree = Tree::instance();
            $tree->init($data, 'pid');
            $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'title');

            $total = count($categorylist);
            $result = array("total" => $total, "rows" => $categorylist);

            return json($result);
        }

        $this->assign('row',$row);
        return $this->fetch();
    }

    /**
     * 添加课程
     */
    public function add_content(){
        $course_id = $this->request->get("course_id");
        $ids = $this->request->get("ids");

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
               
                try {
                    // if($params['type'] == 1){
                    //     $result = AlibabaCloundHelper::instance()->video($params['video_id']);
                    //     if(!$result){
                    //         $this->error('当前视频不存在或已删除');
                    //     }
                    //     $data['type'] = 1;
                    //     $data['media_title'] = $params['video_type']=="audio"?$params['audio_title']:$params['video_name'];
                    //     $data['media_id'] = $result->VideoId;
                    //     $data['duration'] = $result->Duration;
                    //     $data['media_cover'] = empty($result->CoverURL)?'':$result->CoverURL;
                    //     if(empty($params['video_id'])){
                    //         $this->error("请选择视频");
                    //     }
                    // }elseif($params['type'] == 2){
                    //     $data['type'] = 2;
                    //     $data['content'] = $params['content'];

                    //     if(empty($data['content'])){
                    //         $this->error("请上传图文内容");
                    //     }
                    // }else if($params['type'] == 3){
                    //     $result = AlibabaCloundHelper::instance()->video($params['audio_id']);
                    //     if(!$result){
                    //         $this->error('当前音频不存在或已删除');
                    //     }
                    //     $data['type'] = 3;
                    //     $data['media_title'] = $params['audio_title'];
                    //     $data['media_id'] = $result->VideoId;
                    //     $data['duration'] = $result->Duration;

                    //     if(empty($params['audio_id'])){
                    //         $this->error("请选择音频");
                    //     }
                    // }
                    if($params['type'] == 1){
                        // 视频文件
                        $categoryModel = new \app\admin\model\yalimedia\Category();
                        $category      = $categoryModel->where(['id'=>$params['video_id']])->find();
                        
                        $data['media_title'] = $category['title'];
                        $data['media_id']    = $category['id'];
                        $data['type']  = 1;
                        
                    }
                    $data['is_moni']=$params['is_moni'];
                    $data['content'] = $params['content'];
                    $data['type']    = $params['type'];
                    $data['title']   = $params['title'];
                    $data['course_id'] = $course_id;
                    $data['unit_id']=$ids;

                    $courseContentModel = new Content();
                    if($courseContentModel->save($data)){
                        $this->success('请求成功');
                    }else{
                        $this->error("请求失败");
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->fetch();
    }

    /**
     * 编辑目录
     */
    public function edit_content($ids){
        $ids -= 9000;
        $model = new Content();
        $row = $model->get($ids);
        
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            
         
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    // if($params['type'] == 1){
                    //     $result = AlibabaCloundHelper::instance()->video($params['video_id']);
                    //     if(!$result){
                    //         $this->error('当前视频不存在或已删除');
                    //     }

                    //     $data['media_title'] = $params['type']==3?$params['audio_title']:$params['video_name'];
                    //     $data['media_id'] = $result->VideoId;
                    //     $data['duration'] = $result->Duration;
                    //     $data['media_cover'] = empty($result->CoverURL)?'':$result->CoverURL;
                    //     if(empty($params['video_id'])){
                    //         $this->error("请选择视频");
                    //     }
                    // }elseif($params['type'] == 2){
                    //     $data['type'] = 2;
                        // $data['content'] = $params['content'];

                    //     if(empty($data['content'])){
                    //         $this->error("请上传图文内容");
                    //     }
                    // }else if($params['type'] == 3){
                    //     $result = AlibabaCloundHelper::instance()->video($params['audio_id']);
                    //     if(!$result){
                    //         $this->error('当前音频不存在或已删除');
                    //     }

                    //     $data['media_title'] = $params['audio_title'];
                    //     $data['media_id'] = $result->VideoId;
                    //     $data['duration'] = $result->Duration;

                    //     if(empty($params['audio_id'])){
                    //         $this->error("请选择音频");
                    //     }
                    // }
                    
                    $data['content'] = $params['content'];
                    $data['type'] = $params['type'];
                    if($params['type'] == 1){
                        // 视频文件
                        $categoryModel = new \app\admin\model\yalimedia\Category();
                        $category      = $categoryModel->where(['id'=>$params['video_id']])->find();
                        
                        $data['media_title'] = $category['title'];
                        $data['media_id']    = $category['id'];
                        $data['type']  = 1;
                    }
                    $data['is_moni']=$params['is_moni'];
                    $data['title'] = $params['title'];
                    $result = $row->allowField(true)->save($data);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 选择视频文件
     */
    public function select_video(){

        $yalimedia = get_addon_config('yalimedia');
        $config = $yalimedia['ali'];
        if(empty($config['accessKeyId']) || empty($config['accessKeySecret']) || empty($config['regionId'])){
            $this->error(__('请完善插件《课程点播》阿里云视频点播配置项'),'');
        }


        $type = $this->request->param('type',1);

        $search = $this->request->param('search');
        $categoryModel = new \app\admin\model\yalimedia\Category();
        if(!$category = $categoryModel->where(['type'=>$type])->find()){
            if(!$cateId = AlibabaCloundHelper::instance()->add_category($this->type[$type],0)){
                $this->error(__('同步阿里云失败，请稍候再试~'));
            }else{
                $categoryModel = new \app\admin\model\yalimedia\Category();
                $categoryModel->save([
                    'cateid'=>$cateId,
                    'type'=>$type
                ]);
            }
        }else{
            $cateId = $category['cateid'];
        }



        if ($this->request->isAjax())
        {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $cateid = $this->request->get("cateid",$cateId);
            switch($type){
                case "2":
                    $type_name = "audio";
                    break;
                case "3":
                    $type_name = "video";
                    break;

            }
            $match = "CateId=".$cateid;
            if($search){
                $match.=" and Title = '".$search."'";
            }

            $list = AlibabaCloundHelper::instance()->searchMedia($type_name,$match,($offset/$limit)+1,$limit);
            $total = empty($list->Total)?0:$list->Total;


            $list = empty($list->MediaList)?[]:$list->MediaList;


            foreach($list as &$v){
                switch ($v->MediaType){
                    case "audio":
                        $v->AudioTitle = $v->Audio->Title;
                        $v->Status = $v->Audio->Status;
                        $v->Size =  AlibabaCloundHelper::instance()->getFilesize($v->Audio->Size);
                        $v->CreationTime = date("Y-m-d H:i:s",strtotime($v->Audio->CreationTime));
                        break;
                    case "video":
                        $v->VideoTitle = $v->Video->Title;
                        $v->VideoId = $v->Video->VideoId;
                        $v->Status = $v->Video->Status;
                        $v->Size =  empty($v->Video->Size)?'':AlibabaCloundHelper::instance()->getFilesize($v->Video->Size);
                        $v->CoverURL = empty($v->Video->CoverURL)?'':$v->Video->CoverURL;
                        $v->CreationTime = date("Y-m-d H:i:s",strtotime($v->Video->CreationTime));
                        break;
                }
            }

            $result = array("total" => $total, "rows" => $list);
       
            return json($result);
        }

        switch ($type){
            case "2":
                $type_name = "音频";
                break;
            case "3":
                $type_name = "视频";
                break;
        }
        $this->assign('type',$type);
        $this->assign('type_name',$type_name);

        return $this->view->fetch();
    }



    /**
     * 添加目录
     * @return mixed
     */
    public function add_unit(){
        
        if ($this->request->isPost()) {
            $course_id = $this->request->get("course_id");
            $params = $this->request->post("row/a");
            if ($params) {
                try {

                    $model = new Unit();
                    $result = $model->allowField(true)->save(['course_id'=>$course_id,'unit_name'=>$params['unit_name'],'weigh'=>0]);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->fetch();
    }

    /**
     * 编辑目录
     */
    public function edit_unit($ids){
        $model = new Unit();
        $row = $model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除课程
     */
    public function del_unit($ids){
        $model = new Unit();
        $row = $model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        $model = new Content();
        if($model->where(['unit_id'=>$ids])->find()){
            $this->error(__('请先删除当前目录下的课程'));
        }
        if($row->delete()){
            $this->success("请求成功");
        }else{
            $this->error('删除失败');
        }
    }


    /**
     * 删除课程
     */
    public function del_content($ids=""){
        
        $ids -= 9000;
        $model = new Content();
        $row = $model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        if($row->delete()){
            //  删除试题列表
            $ids += 9000;
            $cate = CourseQuestionCategoryModel::where('content_id',$ids)->find();
            if(!empty($cate)){
                CourseQuestionCategoryModel::where('id',$cate['id'])->delete();
                CourseQuestionModel::where('cate_id',$cate['id'])->delete();
            }
            $this->success("请求成功");
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * 删除课程
     */
    public function del($ids=""){

        $model = new \app\admin\model\yalimedia\Course();
        $row   = $model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $model = new Content();
        if($model->where(['course_id'=>$ids])->find()){
            $this->error('当前课程下存在章节，请删除章节后继续操作！');
        }

        $model = new \app\admin\model\yalimedia\course\Unit();
        if($model->where(['course_id'=>$ids])->find()) {
            $this->error('当前课程下存在章节，请删除章节后继续操作！');
        }

        if($row->delete()){
            CourseQuestionModel::where('course_id',$ids)->delete();
            $this->success("请求成功");
        }else{
            $this->error('删除失败');
        }
    }

    /**
     * 添加题库
     *
     * @return void
     */
    public function add_question(){

        // 获取分类ID
        $course_id = Cache::get('select_question');
        if(empty($course_id)){
            $this->error('请刷新！'); 
        }

        $ids    = input('id');
        $insert = explode(',',$ids);

         // 有重复的就挨个添加补充
         foreach($insert as $va){
            try{
                
                $data = [
                    'course_id'     => input('course_id'),
                    'cate_id'       => $course_id,
                    'question_id'   => $va,
                    'createtime'    => time(),
                    'updatetime'    => time()
                ];
                CourseQuestion::insert($data);
            }catch(\Exception $e){
            }
        }
        
        $this->success("添加成功"); 
    }

}
